package com.atguigu.gmall.auth.controller;

import com.atguigu.gmall.auth.service.AuthService;
import org.apache.commons.lang.ArrayUtils;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;

@Controller
@RequestMapping("/")
public class AuthController {
    @Autowired
    AuthService authService;
    //2、登录接口： post方式 访问，登录成功重定向回到redirectUrl的页面
    @PostMapping("login")
    public String login(@RequestParam("returnUrl")String returnUrl,
                        @RequestParam("loginName")String loginName,
                        @RequestParam("password")String password,
                        HttpServletRequest request,
                        HttpServletResponse response,
                        Model model
                        ){
        try {
            //如果登录成功：将用户id转为jwttoken设置到响应头中
            authService.login(loginName , password,request , response);
            //returnUrl=http://search.gmall.com/search?keyword=手机
            String[] splits = returnUrl.split("\\?");
            //"http://search.gmall.com/search"   "keyword=手机"
            String url = splits[0]; //"http://search.gmall.com/search"
            if(ArrayUtils.isNotEmpty(splits) && splits.length==2){
                //returnUrl有参数
                //"keyword=手机"
                String[] kvs = splits[1].split("=");
                String key = kvs[0];
                String encodeVal = URLEncoder.encode(kvs[1], "UTF-8");
                url = url+"?"+key+"="+encodeVal;
            }
            System.out.println("url : "+ url);
            return "redirect:"+ url;//登录成功回到登录之前的页面
        } catch (Exception e) {
            e.printStackTrace();
            //出现异常登录失败  将失败的原因存到域中 跳转到登录页面显示
            model.addAttribute("returnUrl",returnUrl);
            return "login";

        }
    }
    //1、转发到登录页面
    //toLogin.html?returnUrl=http://www.gmall.com/
    @GetMapping("toLogin.html")
    public String toLogin(@RequestParam("returnUrl") String returnUrl,
                          Model model,HttpServletRequest request) throws UnsupportedEncodingException {

        //login页面需要获取使用
        model.addAttribute("returnUrl",returnUrl);
        return "login";
    }
}
